<template>
  <div>
    <nav-bar title="评论" @click-left="navigateToHome" />
    <p class="td">发布人：<el-input class="v"  v-model="userInput" style="margin-left: 20px;" /></p>
    <p class="ts">
      发布内容：
      <el-input class="ipy" v-model="commentInput" cols="30" rows="6" type="textarea" />
    </p>
    <p class="js">
      <el-button type="danger" class="el" @click="postComment">评论</el-button>
    </p>

    <ul>
      <li v-for="comment in comments" :key="comment.id">
        <p>{{ comment.user }}</p>
        <h1>{{ comment.date }}</h1>
        <p>{{ comment.info }}</p>
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
// 假设你有一个 NavBar 组件  
// import NavBar from './NavBar.vue';  
import { ElMessage } from 'element-plus'
// 响应式数据  
const router=useRouter()
const userInput = ref<string>('');
const commentInput = ref<string>('');
const comments: any = ref<Array<{
  id: number;
  user: string;
  info: string;
  date: string;
}>>(JSON.parse(sessionStorage.getItem('comments')) || []);

// 格式化评论内容  
function formatComment(text: any) {
  const reg = /[法轮功共产党爱情垃圾鸡@#￥%……&*()]/g;
  return text.replace(reg, '*');
}

// 导航到首页  
const navigateToHome = () => {
  const router = useRouter();
  router.push('/');
};

// 发表评论  
const postComment = () => {
  if (!userInput.value || !commentInput.value) {

    return;
  }

  const newComment = reactive({
    id: Date.now(),
    user: userInput.value,
    info: formatComment(commentInput.value),
    date: new Date().toLocaleDateString(),
  });
  
     comments.value.unshift(newComment);
  // 保存评论到 sessionStorage  
  sessionStorage.setItem('comments', JSON.stringify(comments.value));
  // 清除输入框内容  
  userInput.value = '';
  commentInput.value = '';
  if( comments.value){
  ElMessage({
    showClose: true,
    message: 'Comment content publishing completed.',
    type: 'success',
  })

  // router.push('/pizhu')
  }


};

// 直接暴露给模板的变量和方法  
defineExpose({
  userInput,
  commentInput,
  comments,
  navigateToHome,
  postComment,
});
</script>

<style lang='scss' scoped>
.v{
  width: 50%;
  
}
.ipy{
  width: 50vw;
  margin-top: 5px;
}
.comment {
  width: 100vw;
  height: 100vh;
  background: #eee;
  overflow: hidden;
  margin-left: 10px;
 
}

.ts {
  margin-left: 10px
}

.js {
  margin-left: 10px
}
.td{
  margin-left: 11px;
}
.el{
  width: 7vw;
  text-align: center;
  margin-left: 734px;
  margin-top: 14px 
}

ul{
  width: 100%;
  height: 30px;
  margin-left: 10px;
  line-height: 30px;
}

</style>